package com.example;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

/**
 * 代码注册BroadcastReceiver
 */
public class MyActivity extends Activity {

    private BroadcastReceiver smsReceiver;

    private static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button register = (Button) findViewById(R.id.broadcast_re_button);
        Button unregister = (Button) findViewById(R.id.broadcast_unre_button);

        register.setOnClickListener(new RegisterOnClickListener());
        unregister.setOnClickListener(new UnRegisterOnClickListener());
    }


    private class RegisterOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {

            // create reciever object
            smsReceiver = new SmsBroadcastReceiver();

            //create intentfilter object
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(SMS_ACTION);

            System.out.println("begin to register myActivity to smsReceiver....");
            MyActivity.this.registerReceiver(smsReceiver, intentFilter);
        }
    }

    private class UnRegisterOnClickListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            System.out.println("begin to unregister myActivity to smsReceiver....");

            MyActivity.this.unregisterReceiver(smsReceiver);
        }
    }
}
